package com.example.service;


import com.example.entity.Role;
import com.example.model.RoleQo;
import com.example.repository.RoleRepository;
import com.example.repository.parameter.LinkEnum;
import com.example.repository.parameter.Operator;
import com.example.repository.parameter.PredicateBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleService {
    @Autowired
    private RoleRepository roleRepository;


    public Role findById(Long id) {
        return roleRepository.findOne(id);
    }


    public Role create(Role role) {
        return roleRepository.save(role);
    }


    public Role update(Role role) {
        return roleRepository.save(role);
    }


    public void delete(Long id) {
        roleRepository.delete(id);
    }

    public List<Role> findAll(){
        List<Role> roleList = roleRepository.findAll();

        return roleList;
    }

    public Page<Role> findPage(RoleQo roleQo){
       Pageable pageable = new PageRequest(roleQo.getPage(), roleQo.getSize(), new Sort(Sort.Direction.ASC, "id"));

        PredicateBuilder pb  = new PredicateBuilder();

        if (!StringUtils.isEmpty(roleQo.getName())) {
            pb.add("name","%" + roleQo.getName() + "%", LinkEnum.LIKE);
        }

        Page<Role> pages = roleRepository.findAll(pb.build(), Operator.AND, pageable);
        return pages;
    }

    public List<Role> findRolesByPid(Long pid){

        List<Role> roles = new ArrayList<Role>();

        String sql = "SELECT r.* from role_permission rp" +

                "INNER JOIN role r ON rp.role_id = r.id" +
                "WHERE rp.permission_id = ?";

        Object ids[] = new Object[1];
        ids[0] = pid;
        roles = roleRepository.findAllByNativeSql(sql,ids);

        return roles;

    }

}
